package collectormsg

import (
	"context"
	"encoding/json"
	"errors"
	kithttp "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"net/http"
)

func MakeQueryHandler(dos OrganizationService, ts TopParamsService, dcs CollectorService) http.Handler {
	getUserHandler := kithttp.NewServer(
		makeGetOrganizationEndpoint(dos),
		decodeGetOrganizationUsersRequest,
		kithttp.EncodeJSONResponse)
	getCollectorHandler := kithttp.NewServer(
		makeGetCollectorEndpoint(dcs),
		decodeGetCollectorRequest,
		kithttp.EncodeJSONResponse)
	topParamsHandler := kithttp.NewServer(
		makeTopParamsEndpoint(ts),
		decodeTopParamsRequest,
		kithttp.EncodeJSONResponse)
	r := mux.NewRouter()
	r.Handle("/api/v1/query/users_by_working_address", getUserHandler).Methods("GET")
	r.Handle("/api/v1/query/collectors_by_users", getCollectorHandler).Methods("GET")
	r.Handle("/api/v1/query/top_query_params", topParamsHandler).Methods("POST")
	return r
}

func decodeGetCollectorRequest(_ context.Context, r *http.Request) (interface{}, error) {
	err := r.ParseForm()
	if err != nil {
		return nil, errors.New("参数不正确")
	}
	userId := r.Form.Get("userId")
	organizationId := r.Form.Get("organizationId")
	return getCollectorRequest{UserId: userId, OrganizationId: organizationId}, nil
}

func decodeGetOrganizationUsersRequest(_ context.Context, r *http.Request) (interface{}, error) {
	err := r.ParseForm()
	if err != nil {
		return nil, errors.New("参数不正确")
	}
	id := r.Form.Get("id")
	return getOrganizationUsersRequest{Id: id}, nil
}

func decodeTopParamsRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var body struct {
		Data []string `json:"data"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		return nil, errors.New("参数不正确")
	}
	return body.Data, nil
}
